<template>
  <div>
    <el-alert title="添加商品信息" :closable="false" type="warning" show-icon>
    </el-alert>
    <!-- 步骤条区域 -->
    <el-steps
      :active="activeName - 0"
      :space="200"
      finish-status="success"
      align-center
    >
      <el-step title="基本信息"> </el-step>
      <el-step title="商品参数"> </el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- tab 区域 -->
    <el-form
      :model="addGoodsForm"
      :rules="addGoodsRules"
      ref="addGoodsRef"
      label-position="top"
    >
      <el-tabs
        v-model="activeName"
        :tab-position="'left'"
        :before-leave="beforeTabChange"
        @tab-click="tabClicked"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input
              v-model="addGoodsForm.goods_price"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input
              v-model="addGoodsForm.goods_number"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input
              v-model="addGoodsForm.goods_weight"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="goodsCateList"
              :props="optionsCate"
              @change="handleChange"
              clearable
              change-on-select
            >
            </el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            v-for="item in manyTableList"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                v-for="(itemArrt, index) in item.attr_vals"
                :key="index"
                :label="itemArrt"
                border
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyTableList"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerObj"
            :on-success="onPictureSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="addGoodsForm.goods_introduce" />
          <el-button type="primary" class="btnClass" @click="add"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog
      title="预览图片"
      :visible.sync="previewImageVisiable"
      width="50%"
      @close="previewImageClose"
    >
      <img :src="previewPath" alt="" srcset="" class="previewStyle" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  props:[],
  data() {
    return {
      activeName: '0',
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [], // 图片数组
        goods_introduce: '',
        attrs: [],
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      goodsCateList: [],
      selectedKeys: [],
      currentParentList: [], // 父级数据列表
      optionsCate: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      onlyTableList: [],
      manyTableList: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      previewPath: '',
      previewImageVisiable: false,
      goodsObj:''
    }
  },
  created() {
    this.getCateList()
    this.goodsObj = this.$route.params.goodsObj;
    console.log(this.goodsObj);
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('/categories', {
        params: this.cateInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      //   console.log(res)
      this.goodsCateList = res.data
    },
    // 级联选择器变化触发的函数
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
        return
      }
    },
    beforeTabChange(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择分类数据')
        return false
      }
    },
    tabClicked() {
      // 商品分类
      if (this.activeName === '1') {
        this.getCateParamsList('many')
      } else if (this.activeName === '2') {
        this.getCateParamsList('only')
      }
    },
    // 获取商品动态参数列表
    async getCateParamsList(activeName) {
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes`,
        { params: { sel: activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息失败！')
      }
      if (activeName === 'many') {
        res.data.forEach((element) => {
          element.attr_vals = element.attr_vals
            ? element.attr_vals.split(',')
            : []
        })
      }
      if (activeName == 'only') {
        this.onlyTableList = res.data
        console.log(this.onlyTableList)
      } else {
        this.manyTableList = res.data
        console.log(this.manyTableList)
      }
    },
    // 预览图片函数
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewImageVisiable = true
    },
    // 图片删除函数
    handleRemove(file) {
      const filePath = file.response.data.tem_path
      const index = this.addGoodsForm.pics.findIndex((item) => {
        item.pic === filePath
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功的回调函数
    onPictureSuccess(response) {
      const picInfo = {
        pic: response.data.tmp_path,
      }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 关闭图片
    previewImageClose() {
      this.previewImageVisiable = false
    },
    // 提交表单
    add() {
      this.$refs.addGoodsRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error('请检查表单项是否填写完整！')
          return
        }
        // 处理添加操作 数据处理
        this.manyTableList.forEach((item) => {
          let newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(','),
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        this.onlyTableList.forEach((item) => {
          let newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 深拷贝 lodash.cloneDeep
        const from = _.cloneDeep(this.addGoodsForm)
        from.goods_cat = from.goods_cat.join(',')
        console.log(from)
        const { data: res } = await this.$http.post(`goods`, from)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！')
        }
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewStyle {
  width: 100%;
}
.btnClass {
  margin: 10px 0px;
}
</style>